package com.appspot.kiyoshiro.kei3.controller.table;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;

import com.appspot.kiyoshiro.kei3.model.User;
import com.appspot.kiyoshiro.kei3.model.Table;
import com.appspot.kiyoshiro.kei3.model.User.Role;
import com.appspot.kiyoshiro.kei3.service.JsonService;
import com.appspot.kiyoshiro.kei3.service.JsonService.JsonStatus;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class PutController extends Controller {
	
    private static final String TABLE_NAME = "table-name";

	@Override
    public Navigation run() throws Exception {
    	
    	JsonService json = new JsonService();
    	
    	// check google-user
    	UserService userService = UserServiceFactory.getUserService();
    	if(userService.isUserLoggedIn()){
    		String account = userService.getCurrentUser().getEmail().replace("@gmail.com", "");
    		
        	// validation
        	Validators v = new Validators(request);
        	v.add(TABLE_NAME, v.required("required"), v.maxlength(20, "maxlength"));
        	
        	if (v.validate()) {
        		// OK
        		// put datastore
        		GlobalTransaction gtx = Datastore.beginGlobalTransaction();
            	
        		Table table = new Table();
            	table.setName(asString(TABLE_NAME));
            	gtx.put(table);
            	
            	User user = new User();
            	user.setAccount(account);
            	user.setRole(Role.MANAGER);
            	user.setApprove(true);
            	user.getTableRef().setModel(table);
            	gtx.put(user);
            	
            	gtx.commit();
            	
            	json.setStatus(JsonStatus.SUCCESS);
            	json.setData(table);
            } else {
        	    //NG
        	    json.setStatus(JsonStatus.INPUT_INVALID);
            	json.setData(v.getErrors());
        	}    		
    	}else{
    		json.setStatus(JsonStatus.GOOGLE_AUTH_FAILED);
        	json.setData(userService.createLoginURL("login-success.html"));
    	}
    	    	
    	json.out(response);
    	return null;
    }
}
